package com.zhp.web;

import com.zhp.pojo.HUser;
import com.zhp.pojo.HUserinfo;
import com.zhp.service.UserService;
import com.zhp.service.impl.UserServiceImpl;
import com.zhp.utils.MD5Util;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @date 2023/4/11
 * @desc 注册功能
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接受 注册的表单数据
        //当表单数据过多时  可以使用下面的方式
        //以表单项的name 位key 以值为value
        Map<String, String[]> parameterMap = req.getParameterMap();

        HUser hUser = new HUser();
        HUserinfo hUserinfo = new HUserinfo();

        //这里 咱们借助BeanUtils 工具类 来拷贝对象间的属性
        try {
            // 把map 中的键值 赋值给user 对象的属性    当map的 键 等于 user的属性时
            BeanUtils.populate(hUser,parameterMap);
            BeanUtils.populate(hUserinfo,parameterMap);

            hUser.setUi(hUserinfo);

            String pwd = MD5Util.EncoderPwdByMd5(hUser.getUpwd());
            hUser.setUpwd(pwd);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        UserService userService = new UserServiceImpl();

        int result = userService.register(hUser);

        if(result==1){
            //注册成功  跳转到登录页面
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else{
            //注册失败
            req.setAttribute("reg_info","注册失败");
            req.getRequestDispatcher("/reg.jsp").forward(req,resp);
        }
    }
}
